#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime
from controls.data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

"""sight_base collection has
    sightid:         景点id（int）
    name:            景点名字拼音（string）
    cname:           景点名字汉字（string）
"""

sight_base_table_dict = {}


class SightBaseTables(object):
    def make_table(self, p_cityid):
        if sight_base_table_dict.has_key(p_cityid):
            return sight_base_table_dict[p_cityid]

        class SightBaseItem(object):
            def __init__(self, p_cityid):
                self.cityid = p_cityid

            def to_dict(self):
                res = {}
                res['sightid'] = self.sightid
                res['name'] = self.name
                res['cname'] = self.cname
                return res

            def __repr__(self):
                return "%d" % (self.sightid)

        metadata = MetaData()
        sight_base_item_table = Table(
            'sight_base_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('sightid', Integer, index=True, nullable=False, unique=True),
            Column('name', Unicode(65), index=True, nullable=False),
            Column('cname', Unicode(65), index=True, nullable=False),
        )
        mapper(SightBaseItem, sight_base_item_table)
        table = {'metadata': metadata,
                 'table': sight_base_item_table,
                 'class': SightBaseItem}
        sight_base_table_dict[p_cityid] = table
        return table


def create_sight_base_item_table_if_not_exist(p_cityid):
    table = SightBaseTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


def add_sight_base_item(p_cityid, p_item):
    table = SightBaseTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.sightid = p_item['sightid']
    item.name = p_item['name']
    item.cname = p_item['cname']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def update_sight_base_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = SightBaseTables().make_table(p_cityid)
    try:
        updateField = {
            table['class'].name: p_item['name'],
            table['class'].cname: p_item['cname']
        }
        session = Session()
        session.query(table['class']).filter(table['class'].sightid == p_item['sightid']).update(updateField,
                                                                                                 synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def delete_sight_base_item(p_cityid, p_sightid):
    if not (p_cityid and p_sightid):
        return False
    table = SightBaseTables().make_table(p_cityid)
    try:
        session = Session()
        session.query(table['class']).filter(table['class'].sightid == p_sightid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_sight_base_all(p_cityid):
    try:
        session = Session()
        table = SightBaseTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by().all()
        res = {}
        for item in items:
            res[item.sightid] = item.to_dict()
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_sight_base_by_sightid(p_cityid, p_sightid):
    try:
        session = Session()
        table = SightBaseTables().make_table(p_cityid)
        item = session.query(table['class']).filter_by(sightid=p_sightid).first()

        res = item.to_dict() if item else None
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    test_city = 1
    create_sight_base_item_table_if_not_exist(test_city)
    test_item = {'sightid': 1,
                 'name': 'test',
                 'cname': 'test',
                 }
    add_sight_base_item(test_city, test_item)
    print get_sight_base_all(test_city)
